import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'model.dart';


//-------------------------------请求文件--------------------------------

 //获取信件
Future<List<Album>> fetchAlbum() async {
  final response = await http.get('http://47.98.213.40/50/');

  print(response.body);

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return compute(parseAlbum,response.body); //Album.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}


//参数化
List<Album> parseAlbum(String responseBody) {

  final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
  return parsed.map<Album>((json) => Album.fromJson(json)).toList();
}




//登录
Future<Login> loginAlbum(String user,String password) async {
  final http.Response response  = await http.post( 'http://47.98.213.40/50/login.php',
      body:({
        'user': user,
        'password':password,
      })

  );

  if (response.statusCode == 200) {

    return Login.fromJson(jsonDecode(response.body));
  } else {

    throw Exception('Failed to update album.');
  }
}


//删除
Future<Login> deleteAlbum(String id) async {
  final http.Response response  = await http.post( 'http://47.98.213.40/50/del.php',
      body:({
        'id': id,
      })

  );

  if (response.statusCode == 200) {

    return Login.fromJson(jsonDecode(response.body));
  } else {

    throw Exception('Failed to update album.');
  }
}


//发送信件
Future<Login> sendAlbum(String send,String value,String form) async {
  print(send);
  print(value);
  final http.Response response  = await http.post( 'http://47.98.213.40/50/send.php',
      body:({
        'asend': send,
        'avalue':value,
        'form':form,
      })

  );

  if (response.statusCode == 200) {

    return Login.fromJson(jsonDecode(response.body));
  } else {

    throw Exception('Failed to update album.');
  }
}
